﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace Catsland.Core
{
    public class PrefabList : UniqueList<GameObject>
    {
        public override void AddItem(string key, GameObject value)
        {
            base.AddItem(key, value);
            if (Mgr<GameEngine>.Singleton._gameEngineMode == GameEngine.GameEngineMode.MapEditor)
            {
                Mgr<GameEngine>.Singleton.Editor.UpdatePrefabList(this);
            }
        }

        public override void RemoveItem(string key)
        {
            base.RemoveItem(key);
            if (Mgr<GameEngine>.Singleton._gameEngineMode == GameEngine.GameEngineMode.MapEditor)
            {
                Mgr<GameEngine>.Singleton.Editor.UpdatePrefabList(this);
            }
        }

        public bool SaveToNode(XmlNode node, XmlDocument doc)
        {
            XmlElement prefabs = doc.CreateElement("Prefabs");
            node.AppendChild(prefabs);

            if (m_list != null)
            {
                foreach (KeyValuePair<string,GameObject> keyValue in m_list)
                {
                    keyValue.Value.SaveToNode(prefabs, doc);
                }
            }
            return true;
        }

        static public PrefabList LoadFromNode(XmlNode prefabs, Scene scene)
        {
            PrefabList prefabList = new PrefabList();

            // LoadFromNode
            foreach (XmlNode gameObject in prefabs.ChildNodes)
            {
                GameObject newGameObject = GameObject.LoadFromNode(gameObject, scene);
                prefabList.AddItem(newGameObject.Name, newGameObject);
            }

            if (Mgr<GameEngine>.Singleton._gameEngineMode == GameEngine.GameEngineMode.MapEditor)
            {
                Mgr<GameEngine>.Singleton.Editor.UpdatePrefabList(prefabList);
            }

            return prefabList;
        }
    }
}
